/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.aplink.generic.bitmap;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.ref.WeakReference;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.Log;

import com.aplink.sg.BuildConfig;

/**
 * A simple subclass of {@link ImageResizer} that fetches and resizes images
 * fetched from a URL.
 */
public class ImageFetcher extends ImageResizer {
    private static final int DISK_CACHE_INDEX = 0;
    private static final String HTTP_CACHE_DIR = "http";
    private static final int HTTP_CACHE_SIZE = 10 * 1024 * 1024; // 10MB
    private static final int IO_BUFFER_SIZE = 8 * 1024;

    private static final String TAG = "ImageFetcher";

    /**
     * Workaround for bug pre-Froyo, see here for more info:
     * http://android-developers.blogspot.com/2011/09/androids-http-clients.html
     */
    public static void disableConnectionReuseIfNecessary() {
        // HTTP connection reuse which was buggy pre-froyo
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
            System.setProperty("http.keepAlive", "false");
        }
    }

    private WeakReference<Context> mContext;
    private File mHttpCacheDir;
    private DiskLruCache mHttpDiskCache;
    private final Object mHttpDiskCacheLock = new Object();

    private boolean mHttpDiskCacheStarting = true;

    /**
     * Initialize providing a single target image size (used for both width and
     * height);
     * 
     * @param context
     * @param imageSize
     */
    public ImageFetcher(final Context context, final int imageSize) {
        super(context, imageSize);
        init(context);
    }

    /**
     * Initialize providing a target image width and height for the processing
     * images.
     * 
     * @param context
     * @param imageWidth
     * @param imageHeight
     */
    public ImageFetcher(final Context context, final int imageWidth,
            final int imageHeight) {
        super(context, imageWidth, imageHeight);
        init(context);
    }

    /**
     * Simple network connection check.
     * 
     * @param context
     */
    private void checkConnection(final Context context) {
        final ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if ((networkInfo == null) || !networkInfo.isConnectedOrConnecting()) {

        }
    }

    @Override
    protected void clearCacheInternal() {
        super.clearCacheInternal();
        synchronized (this.mHttpDiskCacheLock) {
            if ((this.mHttpDiskCache != null)
                    && !this.mHttpDiskCache.isClosed()) {
                try {
                    this.mHttpDiskCache.delete();
                    if (BuildConfig.DEBUG) {
                        Log.d(ImageFetcher.TAG, "HTTP cache cleared");
                    }
                } catch (final IOException e) {
                    Log.e(ImageFetcher.TAG, "clearCacheInternal - " + e);
                }
                this.mHttpDiskCache = null;
                this.mHttpDiskCacheStarting = true;
                initHttpDiskCache();
            }
        }
    }

    @Override
    protected void closeCacheInternal() {
        super.closeCacheInternal();
        synchronized (this.mHttpDiskCacheLock) {
            if (this.mHttpDiskCache != null) {
                try {
                    if (!this.mHttpDiskCache.isClosed()) {
                        this.mHttpDiskCache.close();
                        this.mHttpDiskCache = null;
                        if (BuildConfig.DEBUG) {
                            Log.d(ImageFetcher.TAG, "HTTP cache closed");
                        }
                    }
                } catch (final IOException e) {
                    Log.e(ImageFetcher.TAG, "closeCacheInternal - " + e);
                }
            }
        }
    }

    /**
     * Download a bitmap from a URL and write the content to an output stream.
     * 
     * @param urlString
     *            The URL to fetch
     * @return true if successful, false otherwise
     * @throws IOException
     */
    public boolean downloadUrlToStream(final String urlString,
            final OutputStream outputStream) throws IOException {
        ImageFetcher.disableConnectionReuseIfNecessary();
        BufferedOutputStream out = null;
        BufferedInputStream in = null;
        boolean result = false;
        try {
            in = getInputStream(this.mContext.get(), urlString);
            out = new BufferedOutputStream(outputStream,
                    ImageFetcher.IO_BUFFER_SIZE);
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            result = true;
        } catch (final IOException e) {

        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
        return result;
    }

    @Override
    protected void flushCacheInternal() {
        super.flushCacheInternal();
        synchronized (this.mHttpDiskCacheLock) {
            if (this.mHttpDiskCache != null) {
                try {
                    this.mHttpDiskCache.flush();
                    if (BuildConfig.DEBUG) {
                        Log.d(ImageFetcher.TAG, "HTTP cache flushed");
                    }
                } catch (final IOException e) {
                    Log.e(ImageFetcher.TAG, "flush - " + e);
                }
            }
        }
    }

    private BufferedInputStream getInputStream(final Context context,
            String urlString) throws IOException {
        if (urlString.contains("@Assert://")) {
            urlString = urlString.replace("@Assert://", "");
            return new BufferedInputStream(context.getAssets().open(urlString),
                    ImageFetcher.IO_BUFFER_SIZE);
        }
        return new BufferedInputStream(new FileInputStream(urlString),
                ImageFetcher.IO_BUFFER_SIZE);
    }

    private void init(final Context context) {
        checkConnection(context);
        this.mContext = new WeakReference<Context>(context);
        this.mHttpCacheDir = ImageCache.getDiskCacheDir(context,
                ImageFetcher.HTTP_CACHE_DIR);
    }

    @Override
    protected void initDiskCacheInternal() {
        super.initDiskCacheInternal();
        initHttpDiskCache();
    }

    private void initHttpDiskCache() {
        if (!this.mHttpCacheDir.exists()) {
            this.mHttpCacheDir.mkdirs();
        }
        synchronized (this.mHttpDiskCacheLock) {
            if (ImageCache.getUsableSpace(this.mHttpCacheDir) > ImageFetcher.HTTP_CACHE_SIZE) {
                try {
                    this.mHttpDiskCache = DiskLruCache.open(this.mHttpCacheDir,
                            1, 1, ImageFetcher.HTTP_CACHE_SIZE);
                    if (BuildConfig.DEBUG) {
                        Log.d(ImageFetcher.TAG, "HTTP cache initialized");
                    }
                } catch (final IOException e) {
                    this.mHttpDiskCache = null;
                }
            }
            this.mHttpDiskCacheStarting = false;
            this.mHttpDiskCacheLock.notifyAll();
        }
    }

    @Override
    protected Bitmap processBitmap(final Object data) {
        return this.processBitmap(String.valueOf(data));
    }

    /**
     * The main process method, which will be called by the ImageWorker in the
     * AsyncTask background thread.
     * 
     * @param data
     *            The data to load the bitmap, in this case, a regular http URL
     * @return The downloaded and resized bitmap
     */
    private Bitmap processBitmap(final String data) {
        if (BuildConfig.DEBUG) {
            Log.d(ImageFetcher.TAG, "processBitmap - " + data);
        }

        final String key = ImageCache.hashKeyForDisk(data);
        FileDescriptor fileDescriptor = null;
        FileInputStream fileInputStream = null;
        DiskLruCache.Snapshot snapshot;
        synchronized (this.mHttpDiskCacheLock) {
            // Wait for disk cache to initialize
            while (this.mHttpDiskCacheStarting) {
                try {
                    this.mHttpDiskCacheLock.wait();
                } catch (final InterruptedException e) {
                }
            }

            if (this.mHttpDiskCache != null) {
                try {
                    snapshot = this.mHttpDiskCache.get(key);
                    if (snapshot == null) {
                        if (BuildConfig.DEBUG) {
                            Log.d(ImageFetcher.TAG,
                                    "processBitmap, not found in http cache, downloading...");
                        }
                        final DiskLruCache.Editor editor = this.mHttpDiskCache
                                .edit(key);
                        if (editor != null) {
                            if (downloadUrlToStream(
                                    data,
                                    editor.newOutputStream(ImageFetcher.DISK_CACHE_INDEX))) {
                                editor.commit();
                            } else {
                                editor.abort();
                            }
                        }
                        snapshot = this.mHttpDiskCache.get(key);
                    }
                    if (snapshot != null) {
                        fileInputStream = (FileInputStream) snapshot
                                .getInputStream(ImageFetcher.DISK_CACHE_INDEX);
                        fileDescriptor = fileInputStream.getFD();
                    }
                } catch (final IOException e) {
                    Log.e(ImageFetcher.TAG, "processBitmap - " + e);
                } catch (final IllegalStateException e) {
                    Log.e(ImageFetcher.TAG, "processBitmap - " + e);
                } finally {
                    if ((fileDescriptor == null) && (fileInputStream != null)) {
                        try {
                            fileInputStream.close();
                        } catch (final IOException e) {
                        }
                    }
                }
            }
        }

        Bitmap bitmap = null;
        if (fileDescriptor != null) {
            bitmap = ImageResizer.decodeSampledBitmapFromDescriptor(
                    fileDescriptor, this.mImageWidth, this.mImageHeight,
                    getImageCache());
        }
        if (fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (final IOException e) {
            }
        }
        return bitmap;
    }
}
